import { getDate } from "@common/src/utils/days.ts";
import { ref } from 'vue'
const splitTimeRangeByMinutes = (
    startTime: string,
    endTime: string,
    intervalMinutes: number) => {
    const startTimeObj = new Date(startTime);
    const endTimeObj = new Date(endTime);
    const timeRanges = [];

    // 复制开始时间对象，以便在循环中修改
    let currentTime = new Date(startTimeObj);

    // 当当前时间小于或等于结束时间时，继续循环
    while (currentTime < endTimeObj) {
        // 将当前时间转换为分钟（自午夜起）
        const currentMinute = currentTime.getMinutes();

        // 计算当前时间的小时和分钟部分，但不包括日期
        currentTime.setMinutes(currentMinute - (currentMinute % intervalMinutes));

        // 如果当前时间还没有被添加到数组中，则添加它
        if (
            timeRanges.length === 0 ||
            timeRanges[timeRanges.length - 1].start !== currentTime.getTime()
        ) {
            // 结束时间小于最大时间
            if (
                currentTime.getTime() + intervalMinutes * 60 * 1000 <
                new Date(endTime).getTime()
            ) {
                timeRanges.push({
                    start: getDate(new Date(currentTime), "HH:mm"),
                    end: getDate(
                        new Date(
                            new Date(currentTime.getTime() + intervalMinutes * 60 * 1000)
                        ),
                        "HH:mm"
                    ),
                });
            }
        }

        // 增加间隔分钟数，以便下一次循环
        currentTime.setMinutes(currentTime.getMinutes() + intervalMinutes);
    }

    return timeRanges;
}

const chunkArray = (arr: [], chunkSize = 2) => {
    const chunks = [];
    for (let i = 0; i < arr.length; i += chunkSize) {
        chunks.push(arr.slice(i, i + chunkSize));
    }
    return chunks;
}

const getChckList = (data: {
    [daychecked: string]: string[]
}) => {
    const checkList = []
    for (let key in data) {
        if (data[key]) {
            if (key === "daychecked") {
                data[key].forEach((el: string) => {
                    checkList.push(el);
                });
            } else {
                checkList.push(key);
            }
        }
    }
    return checkList
}

const getTabel = (list_3) => {
    const tableData: any[] = []
    list_3.forEach((item: []) => {
        let val = {} as any;
        item.forEach((el, i) => {
            val[`time${i + 1}`] = el[0].start + "-" + el[0].end;
            val[`num${i + 1}`] = 1;
        }
        );
        tableData.push(val);
    });
    return tableData
}


// 自定义时间 
export const useDate = () => {
    const daysWeek = [
        "星期日",
        "星期一",
        "星期二",
        "星期三",
        "星期四",
        "星期五",
        "星期六",
    ];
    const datePicker = ref(new Date());
    const date = new Date();
    const datePickerText = ref(
        getDate(date, "YYYY-MM-DD") + " " + daysWeek[date.getDay()]
    );
    function getPickerchange() {
        datePickerText.value =
            getDate(new Date(datePicker.value), "YYYY-MM-DD") +
            " " +
            daysWeek[new Date(datePicker.value).getDay()];
    }
    return {
        datePickerText,
        datePicker,
        getPickerchange
    }
}
// table
export const useTable = (
    checkCom: any,
) => {
    const tableColumn = reactive([
        {
            lable: "时间段",
            prop: "time1",
            width: 120,
        },
        {
            lable: "预约人数",
            prop: "num1",
        },
        {
            lable: "时间段",
            prop: "time2",
            width: 120,
        },
        {
            lable: "预约人数",
            prop: "num2",
        },
        {
            lable: "时间段",
            prop: "time3",
            width: 120,
        },
        {
            lable: "预约人数",
            prop: "num3",
        },
        {
            lable: "时间段",
            prop: "time4",
            width: 120,
        },
        {
            lable: "预约人数",
            prop: "num4",
        },
    ]);

    const tableData = ref([])
    const step = ref<number>(10);
    const loading = ref<boolean>(false);
    const custom = ref<boolean>(false);

    const handler = () => {
        const timeYear = "2024-1-1 ";
        const map: {
            [key: string]: string;
        } = {
            am: "8:00-11:30",
            noon: "12:00-14:00",
            af: "14:00-18:00",
            eve: "",
            aftEve: "",
            day: "8:00-24:00",
            dayAll: "0:00-24:00",
        };
        let ranges: any = [];
        // loading.value = true;
        //自定义时间
        if (custom.value) {
        } else {
            const data = checkCom.value.getData();
            const checkList = getChckList(data);
            checkList.forEach((element: string) => {
                if (map[element]) {
                    const start = timeYear + map[element].split("-")[0];
                    const end = timeYear + map[element].split("-")[1];
                    const data = splitTimeRangeByMinutes(start, end, step.value);
                    data.forEach((val) => {
                        ranges.push(val);
                    });
                }
            });
            const list_3 = chunkArray(chunkArray(ranges, 1) as [], 4);
            tableData.value = getTabel(list_3);
            console.log("handler", tableData);
        }
    }
    return {
        loading,
        handler,
        tableData,
        tableColumn,
        step,
        custom
    }
}